import tencentcloud from 'tencentcloud-sdk-nodejs'
import axios from 'axios'
import FormData from 'form-data'
import fs from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 腾讯云配置
const TENCENT_SECRET_ID = process.env.TENCENT_SECRET_ID
const TENCENT_SECRET_KEY = process.env.TENCENT_SECRET_KEY
const TENCENT_REGION = process.env.TENCENT_REGION || 'ap-beijing'

// OCR 客户端
let ocrClient = null
let iaiClient = null

if (TENCENT_SECRET_ID && TENCENT_SECRET_KEY) {
  const OcrClient = tencentcloud.ocr.v20181119.Client
  ocrClient = new OcrClient({
    credential: {
      secretId: TENCENT_SECRET_ID,
      secretKey: TENCENT_SECRET_KEY,
    },
    region: TENCENT_REGION,
  })

  // 人脸识别客户端
  const IaiClient = tencentcloud.iai.v20200303.Client
  iaiClient = new IaiClient({
    credential: {
      secretId: TENCENT_SECRET_ID,
      secretKey: TENCENT_SECRET_KEY,
    },
    region: TENCENT_REGION,
  })
} else {
  console.warn('警告: 未配置腾讯云API密钥，实名认证功能将不可用')
}

/**
 * 识别身份证正面（OCR）
 * @param {string} imageBase64 - 身份证正面图片的Base64编码
 * @returns {Promise<Object>} 识别结果
 */
export async function recognizeIdCardFront(imageBase64) {
  try {
    if (!ocrClient) {
      throw new Error('腾讯云OCR服务未配置，请检查环境变量')
    }

    const params = {
      ImageBase64: imageBase64,
      CardSide: 'FRONT', // 正面
    }

    const response = await ocrClient.IDCardOCR(params)
    
    if (response.Error) {
      throw new Error(`OCR识别失败: ${response.Error.Message}`)
    }

    return {
      success: true,
      data: {
        name: response.Name || '',
        idCard: response.IdNum || '',
        address: response.Address || '',
        birthday: response.Birth || '',
        sex: response.Sex || '',
        nation: response.Nation || '',
      },
      requestId: response.RequestId,
    }
  } catch (error) {
    console.error('身份证正面识别错误:', error)
    throw new Error(`身份证识别失败: ${error.message}`)
  }
}

/**
 * 识别身份证反面（OCR）
 * @param {string} imageBase64 - 身份证反面图片的Base64编码
 * @returns {Promise<Object>} 识别结果
 */
export async function recognizeIdCardBack(imageBase64) {
  try {
    if (!ocrClient) {
      throw new Error('腾讯云OCR服务未配置，请检查环境变量')
    }

    const params = {
      ImageBase64: imageBase64,
      CardSide: 'BACK', // 反面
    }

    const response = await ocrClient.IDCardOCR(params)
    
    if (response.Error) {
      throw new Error(`OCR识别失败: ${response.Error.Message}`)
    }

    return {
      success: true,
      data: {
        authority: response.Authority || '', // 签发机关
        validDate: response.ValidDate || '', // 有效期限
      },
      requestId: response.RequestId,
    }
  } catch (error) {
    console.error('身份证反面识别错误:', error)
    throw new Error(`身份证识别失败: ${error.message}`)
  }
}

/**
 * 人脸比对（将身份证照片与人脸照片进行比对）
 * @param {string} idCardImageBase64 - 身份证照片的Base64编码（从身份证正面提取）
 * @param {string} faceImageBase64 - 用户自拍照片的Base64编码
 * @returns {Promise<Object>} 比对结果
 */
export async function compareFace(idCardImageBase64, faceImageBase64) {
  try {
    if (!iaiClient) {
      throw new Error('腾讯云人脸识别服务未配置，请检查环境变量')
    }

    const params = {
      ImageA: idCardImageBase64,
      ImageB: faceImageBase64,
      FaceModelVersion: '3.0', // 使用最新的人脸识别模型
    }

    const response = await iaiClient.CompareFace(params)
    
    if (response.Error) {
      throw new Error(`人脸比对失败: ${response.Error.Message}`)
    }

    const score = response.Score || 0
    const threshold = 80 // 相似度阈值，80分以上认为匹配

    return {
      success: true,
      data: {
        score: score,
        matched: score >= threshold,
        threshold: threshold,
      },
      requestId: response.RequestId,
    }
  } catch (error) {
    console.error('人脸比对错误:', error)
    throw new Error(`人脸比对失败: ${error.message}`)
  }
}

/**
 * 从URL下载图片并转换为Base64
 * @param {string} imageUrl - 图片URL
 * @returns {Promise<string>} Base64编码的图片
 */
export async function imageUrlToBase64(imageUrl) {
  try {
    // 如果是本地文件路径
    if (imageUrl.startsWith('/') || imageUrl.startsWith('./')) {
      const imagePath = join(__dirname, '..', imageUrl)
      const imageBuffer = fs.readFileSync(imagePath)
      return imageBuffer.toString('base64')
    }

    // 如果是URL，下载图片
    const response = await axios.get(imageUrl, {
      responseType: 'arraybuffer',
    })
    const imageBuffer = Buffer.from(response.data, 'binary')
    return imageBuffer.toString('base64')
  } catch (error) {
    console.error('图片转换错误:', error)
    throw new Error(`图片转换失败: ${error.message}`)
  }
}

/**
 * 验证身份证号码格式
 * @param {string} idCard - 身份证号码
 * @returns {boolean} 是否有效
 */
export function validateIdCard(idCard) {
  if (!idCard || typeof idCard !== 'string') {
    return false
  }

  // 18位身份证号码正则
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  
  if (!reg.test(idCard)) {
    return false
  }

  // 校验码验证
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  
  let sum = 0
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard[i]) * weights[i]
  }
  
  const checkCode = checkCodes[sum % 11]
  return idCard[17].toUpperCase() === checkCode
}

